package be.music.tool.dao.impl;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.transform.stream.StreamResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.stereotype.Repository;

import be.music.tool.dao.GenericDao;

@Repository
public abstract class GenericDaoXStreamImpl<T, V> implements GenericDao<T, V> {

	@Autowired
	private Marshaller oxMarshaller;

	@Autowired
	private Unmarshaller oxUnmarshaller;

	public T find(V id) {
		return null;
	};

	public T save(T object) {

		// TODO: Create template for this?
		// TODO: Definitely create a template for this! :)

		// TODO: getPath is only the base path. A unique identifier should be
		// created for the object, which can be used as filename.

		// TODO: check if the object has an id. If it doesn't, generate one.

		FileOutputStream os = null;
		try {
			os = new FileOutputStream(getBasePath());
			oxMarshaller.marshal(object, new StreamResult(os));
		} catch (FileNotFoundException fnfe) {
			// TODO: Handle exception!!!
		} catch (IOException ioe) {
			// TODO: Handle exception!!!
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					// TODO: Handle exception!!!
				}
			}
		}

		return object;

	}

	protected abstract String getBasePath();

}
